package com.jushu.storbox.util.image;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.util.DeviceUtil;
import com.jushu.storbox.util.FileUtil;
import com.jushu.storbox.util.OnImageDownload;
import com.jushu.storbox.util.PackageUtil;

public class ImageDownloader {  
    private static final String TAG = "ImageDownloader";  
    private HashMap<String, MyAsyncTask> map = new HashMap<String, MyAsyncTask>();  
    private Map<String, SoftReference<Bitmap>> imageCaches = new HashMap<String, SoftReference<Bitmap>>();  
    /** 
     * 
     * @param url
     * @param mImageView
     * @param thumbnailURL
     * @param localityOrService
     * @param path
     * @param context
     * @param download
     */
    public void imageDownload(String url,ImageView mImageView,String thumbnailURL,int localityOrService,String path,Context context,OnImageDownload download){  
    	SoftReference<Bitmap> currBitmap = imageCaches.get(url);  
        Bitmap softRefBitmap = null;  
        if(currBitmap != null){  
            softRefBitmap = currBitmap.get();  
        }  
        String imageName = "";  
        if(url != null){  
            imageName = FileUtil.getImageName(url);  
        }
//        Bitmap bitmap = getBitmapFromFile(context,imageName,path);  
        Bitmap bitmap = BitmapUtil.createImageThumbnail(path + imageName, ClientConfig.LOCAL_THUMBNAIL_WIDTH, ClientConfig.LOCAL_THUMBNAIL_HEIGHT);
        
        if(currBitmap != null && mImageView != null && softRefBitmap != null && url.equals(mImageView.getTag())){  
            mImageView.setImageBitmap(softRefBitmap);  
        }  
        else if(bitmap != null && mImageView != null && url.equals(mImageView.getTag())){  
            mImageView.setImageBitmap(bitmap);  
        }  
        else if(url != null && needCreateNewTask(mImageView))
        {  
            MyAsyncTask task = new MyAsyncTask(url, mImageView,thumbnailURL, localityOrService,path,context,download);  
            if(mImageView != null){  
                PackageUtil.flag ++;  
                task.execute();  
                map.put(url, task);  
            }  
        }  
    }  
      
    /** 
     * @param url 
     * @param mImageView 
     * @return 
     */  
    private boolean needCreateNewTask(ImageView mImageView){  
        boolean b = true;  
        if(mImageView != null){  
            String curr_task_url = (String)mImageView.getTag();  
            if(isTasksContains(curr_task_url)){  
                b = false;  
            }  
        }  
        return b;  
    }  
      
    /** 
     * @param url 
     * @return 
     */  
    private boolean isTasksContains(String url){  
        boolean b = false;  
        if(map != null && map.get(url) != null){  
            b = true;  
        }  
        return b;  
    }  
      
    /** 
     * @param url 
     */  
    private void removeTaskFormMap(String url){  
        if(url != null && map != null && map.get(url) != null){  
            map.remove(url);  
        }  
    }  
      
    /** 
     * @param mActivity  
     * @param imageName 
     * @param path
     * @return 
     */  
    public Bitmap getBitmapFromFile(Context context,String imageName,String path){  
        Bitmap bitmap = null;  
        if(imageName != null){  
            File file = null;  
            String real_path = "";
            FileInputStream fis = null;
            try {  
                if(DeviceUtil.instance().hasSDCard()){  
                    real_path = DeviceUtil.instance().getExtPath() + (path != null && path.startsWith("/") ? path : "/" + path);  
                }else{  
                    real_path = PackageUtil.getInstance().getPackagePath(context) + (path != null && path.startsWith("/") ? path : "/" + path);  
                }  
                file = new File(real_path, imageName);  
                if(file.exists()) {
                	fis = new FileInputStream(file);
                }
                bitmap = BitmapFactory.decodeStream(fis);  
            } catch (Exception e) {  
                e.printStackTrace();  
                bitmap = null;  
            } finally {
            	try {
            		if (null != fis) {
            			fis.close();
            		}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }  
        return bitmap;  
    }  
      
    /** 
     * 
     * @param path
     * @param context
     * @param imageName
     * @param bitmap
     * @return
     */
    private boolean setBitmapToFile(String path,Context context,String imageName,Bitmap bitmap){ 
        File file = null;  
        String real_path = "";  
        try {  
            if(DeviceUtil.instance().hasSDCard()){  
                real_path = DeviceUtil.instance().getExtPath() + (path != null && path.startsWith("/") ? path : "/" + path);  
            }else{  
                real_path = PackageUtil.getInstance().getPackagePath(context) + (path != null && path.startsWith("/") ? path : "/" + path);  
            }  
            file = new File(real_path, imageName);  
            if(!file.exists()){  
                File file2 = new File(real_path + "/");  
                file2.mkdirs();  
            }  
            file.createNewFile();  
            FileOutputStream fos = null;  
            if(DeviceUtil.instance().hasSDCard()){  
                fos = new FileOutputStream(file);  
            }else{  
                fos = context.openFileOutput(imageName, Context.MODE_PRIVATE);  
            }  
              
            if (imageName != null && (imageName.contains(".png") || imageName.contains(".PNG"))){  
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);  
            } 
            else if(imageName != null && (imageName.contains(".JPE") || imageName.contains(".JPEG") ||imageName.contains(".jpe") || imageName.contains(".jpeg"))){  
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);  
            }  
            else
            {
            	bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);  
            }
            fos.flush();  
            if(fos != null){  
                fos.close();  
            }  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  
      
    /** 
     * @param path 
     * @param mActivity 
     * @param imageName 
     */  
    private void removeBitmapFromFile(String path,Context context,String imageName){  
        File file = null;  
        String real_path = "";  
        try {  
            if(DeviceUtil.instance().hasSDCard()){  
                real_path = DeviceUtil.instance().getExtPath() + (path != null && path.startsWith("/") ? path : "/" + path);  
            }else{  
                real_path = PackageUtil.getInstance().getPackagePath(context) + (path != null && path.startsWith("/") ? path : "/" + path);  
            }  
            file = new File(real_path, imageName);  
            if(file != null)  
            file.delete();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
      
    private class MyAsyncTask extends AsyncTask<String, Void, Bitmap>{  
        private ImageView mImageView;  
        private String url;  
        private OnImageDownload download;  
        private String path;  
        private Context context;  
        private String thumbnailURL;
        private int localityOrService = 1;
          
        public MyAsyncTask(String url,ImageView mImageView,String thumbnailURL,int localityOrService,String path,Context context,OnImageDownload download){  
            this.mImageView = mImageView;  
            this.url = url;  
            this.path = path;  
            this.context = context;  
            this.download = download;  
            this.localityOrService = localityOrService;
            this.thumbnailURL = thumbnailURL;
        }  
  
        @Override  
        protected Bitmap doInBackground(String... params) {  
            Bitmap data = null;  
            if(url != null){  
                try {
                	File thumBnail2 = new File(url);
//                	String imageName = null;
//                	if(!thumBnail2.exists())
//                	{
//                		if(thumbnailURL != null)
//                		{
//                			if(localityOrService == 1)
//                			{
////                				URL c_url = new URL(thumbnailURL);  
////                                InputStream bitmap_data = c_url.openStream();  
////                                data = BitmapFactory.decodeStream(bitmap_data);  
//                				data = BitmapUtil.createImageThumbnail(thumBnail2.getAbsolutePath(), ClientConfig.THUMBNAIL_HEIGHT, ClientConfig.THUMBNAIL_HEIGHT);
//                                imageName  = Util.getInstance().getImageName(thumbnailURL); 
//                			}
//                			else if(localityOrService == 2)
//                			{
//                				data = compressImageFromFile(url);  
//                                imageName = Util.getInstance().getImageName(url); 
//                			}
//                		}
//                		else
//                		{
//                			data = compressImageFromFile(url);  
//                            imageName = Util.getInstance().getImageName(url); 
//                		}
//                	}
//                	else
//                	{
//                		data = compressImageFromFile(url);  
//                         imageName = Util.getInstance().getImageName(url);  
//                	}
//                	
//                    if(!setBitmapToFile(path,context,imageName, data))
//                    {   
//                        removeBitmapFromFile(path,context,imageName);  
//                    }  
                	data = BitmapUtil.createImageThumbnail(thumBnail2.getAbsolutePath(), ClientConfig.LOCAL_THUMBNAIL_HEIGHT, ClientConfig.LOCAL_THUMBNAIL_HEIGHT);
                    imageCaches.put(url, new SoftReference<Bitmap>(data));  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
            return data;  
        }  
  
        @Override  
        protected void onPreExecute() {  
            super.onPreExecute();  
        }  
  
        @Override  
        protected void onPostExecute(Bitmap result) {  
            if(download != null){  
                download.onDownloadSucc(result,url,mImageView);  
                removeTaskFormMap(url);  
            }  
            super.onPostExecute(result);  
        }  
          
    }  
    private Bitmap loadImageData(String srcPath)
    {
    	return null;
    }
}  
